package com.ksyun.ks3.services;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpClientRetryInterceptor implements Interceptor {

    private int maxRetry; // 最大重连次数

    public OkHttpClientRetryInterceptor(int maxRetry) {
        this.maxRetry = maxRetry;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        return retry(chain, 0);
    }

    private Response retry(Chain chain, int retryNo) {
        Request request = chain.request();
        Response response = null;
        try {
            response = chain.proceed(request);
        } catch (IOException e) {
            e.printStackTrace();
            if (maxRetry > retryNo) {
                return retry(chain, retryNo + 1);
            }
        } finally {
            return response;
        }
    }


}
